package cn.ulyer.core.secure;

import cn.ulyer.common.oauth.JsonOauthResourceFailHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;


@EnableResourceServer
@Configuration
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    final String RESOURCE_ID = "API_STARTER";

    @Autowired
    private TokenStore tokenStore;



    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        JsonOauthResourceFailHandler jsonOauthResourceFailHandler = new JsonOauthResourceFailHandler();
        resources.resourceId(RESOURCE_ID).tokenStore(tokenStore)
                .accessDeniedHandler(jsonOauthResourceFailHandler)
                .authenticationEntryPoint(jsonOauthResourceFailHandler);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
                .and()
                .cors().and()
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS).permitAll()
                .antMatchers("/swagger-resources/**", "/webjars/**").permitAll()
                .antMatchers("/v2/api-docs-ext/**", "/doc.html").permitAll()
                .antMatchers("/oauth/authorize", "/oauth/token").permitAll()
                .anyRequest().authenticated()
                .and()
                .csrf().disable().httpBasic().disable();
    }
}
